/**
 * 项目名称: Topic_1038.cpp
 * 项目路径: study/DataStructure/LeetCode/树/中等
 * 编辑时间: 2024年08月30日08时13分08秒
 * 用   户: 轻尘
 */

#include <bits/stdc++.h>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    struct tree{
        TreeNode *op;
        int val;
    };
    vector<tree>vn;
    void pre(TreeNode* root){
        if(!root)return;
        tree ol;
        ol.op = root;
        ol.val = 0;
        vn.push_back(ol);
        pre(root->left);
        pre(root->right);
    }
    TreeNode* bstToGst(TreeNode* root) {
        if(!root)return nullptr;
        pre(root);
        for(int i = 0;i<vn.size();i++){
            int mid = vn[i].op->val;
            for(auto y:vn){
                if(mid<=y.op->val){
                    vn[i].val+=y.op->val;
                }
            }
        }
        for(int i = 0;i<vn.size();i++)vn[i].op->val = vn[i].val;

        return root;
    }
};
